package com.groupseven.happycampus.controller;

import com.groupseven.happycampus.common.pojo.Commodity;
import com.groupseven.happycampus.common.result.R;
import com.groupseven.happycampus.common.utils.OssUtils;
import com.groupseven.happycampus.common.vo.LayuiPageVo;
import com.groupseven.happycampus.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

@RestController
@RequestMapping("commodity")
public class CommodityController {

    //增删改查
    @Autowired
    private CommodityService commodityService;

    @RequestMapping("/commodityList")
    public LayuiPageVo<Commodity> commodityLayuiPageVoList(@RequestParam Map<String, Object> params) {

        return commodityService.commodityListPageData(params);
    }

//添加操作
    @RequestMapping("/commodityAdd")
    public R addCommodity(Commodity commodity) {
        System.out.println(commodity);
        int result = commodityService.addCommodity(commodity);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    //上传 文件图片操作
    @RequestMapping("/upload")
    public R uploadPic(MultipartFile file) throws IOException {
        //防止预检请求
        if (file != null){
            // 得到文件名
            String originalFilename = file.getOriginalFilename();
            // 将文件转换为输入流
            InputStream inputStream = file.getInputStream();

            // 通过 uploadFile 方法 将文件上传到阿里云
            // 返回值为 文件存储位置
            String url = OssUtils.uploadFile(inputStream, originalFilename);
            return R.ok().data("url",url);

        }else {
            return R.error();
        }

    }
    @RequestMapping("/deleteCommodity")
    public R deleteCommodity(Integer commodityId){
        // 通过商品 id 删除
        int result = commodityService.deleteCommodity(commodityId);
        if (result == 1){
            return R.ok();
        }else {
            return R.error();
        }
    }
    @RequestMapping("/updateCommodity")
    public R updateCommodity(Commodity commodity){
        System.out.println(commodity);
        int result = commodityService.updateCommodity(commodity);
        if (result == 1){
            return R.ok();
        }else{
            return R.error();
        }
    }






}
